package br.org.groupware_workbench.collablet.news;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.view.Results;
import br.org.groupware_workbench.collabElement.coop.recommendMgr.api.RecommendMgrController;
import br.org.groupware_workbench.collabElement.coop.recommendMgr.api.RecommendMgrInstance;
import br.org.groupware_workbench.collabElementFw.facade.CollabElementInstance;
import br.org.groupware_workbench.collabletFw.facade.CollabletInstance;
import br.org.groupware_workbench.coreutils.GenericEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RequestScoped
@Resource
public class NewsMgrController {

    private final Result result;
    private final HttpServletRequest request;

    public NewsMgrController(Result result, HttpServletRequest request) {
        this.result = result;
        this.request = request;
    }

    @Get
    @Path(value = "/groupware-workbench/{newsMgr}/news")
    public List<News> list(NewsMgrInstance newsMgr) {
        addIncludes(newsMgr);
        return newsMgr.list();
    }

    @Post
    @Get
    @Path(value = "/groupware-workbench/{newsMgr}/news/{id}/show")
    public News show(final CollabletInstance collablet, final NewsMgrInstance newsMgr, final long id) {
        result.include("nameCollablet","news");
        addIncludes(newsMgr);

        if (id == 0) return new News();

        News toReturn = newsMgr.findById(id);

        @SuppressWarnings("unchecked")
        // Cast desnecessário no Java EE 6. Necessário no Java EE 5.
        Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

        for (CollabElementInstance instance : newsMgr.getCollabElementInstances()) {
            String nome = instance.getName();
            Map<String, String[]> collabParams = new HashMap<String, String[]>();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String paramName = param.getKey();
                if (!paramName.startsWith(nome + ".")) continue;
                collabParams.put(paramName.substring(nome.length() + 1), param.getValue());
            }
            instance.saveWidgets(collabParams, toReturn.getId());
        }

        return toReturn;
    }

    @Get
    @Path(value = "/groupware-workbench/{newsMgr}/news/{id}")
    public News retrieve(NewsMgrInstance newsMgr, long id) {
        addIncludes(newsMgr);
        if (id != 0) return newsMgr.findById(id);
        return new News();
    }

    @Post
    @Path(value = "/groupware-workbench/{newsMgr}/news")
    public void save(NewsMgrInstance newsMgr, final News news) {
        newsMgr.save(news);

        @SuppressWarnings("unchecked")
        // Cast desnecessário no Java EE 6. Necessário no Java EE 5.
        Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

        for (CollabElementInstance instance : newsMgr.getCollabElementInstances()) {
            String nome = instance.getName();
            Map<String, String[]> collabParams = new HashMap<String, String[]>();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String paramName = param.getKey();
                if (!paramName.startsWith(nome + ".")) continue;
                collabParams.put(paramName.substring(nome.length() + 1), param.getValue());
            }
            instance.saveWidgets(collabParams, news.getId());
        }

        RecommendMgrController recommendMgr = new RecommendMgrController(result);
        List<News> newsList = newsMgr.list();
        List<GenericEntity> newsListGE = new ArrayList<GenericEntity>();
        for (News news2 : newsList) {
            newsListGE.add(news2);
        }
        recommendMgr.generateRecommend(newsMgr.getCollabElementInstance(RecommendMgrInstance.class), newsMgr, newsListGE, news);
        result.use(Results.logic()).redirectTo(NewsMgrController.class).list(newsMgr);
    }

    @Delete
    @Path(value = "/groupware-workbench/{collablet}/news/{news.id}")
    public void delete(NewsMgrInstance collablet, final News news) {
        collablet.delete(news.getId());
        result.use(Results.logic()).redirectTo(NewsMgrController.class).list(collablet);
    }

    private void addIncludes(NewsMgrInstance collablet) {
        result.include("newsMgr", collablet);
        for (CollabElementInstance collabComponentInstance : collablet.getCollabElementInstances()) {
            String nomeComponente = collabComponentInstance.getName();
            result.include(nomeComponente, collabComponentInstance);
            System.out.println("O componente " + collabComponentInstance.getComponent().getCod() +
                    " foi adicionado na requisição com o nome " + nomeComponente);
        }
    }
}